<template>
  <a-layout>
    <a-layout-content style="padding: 24px;">
      <div class="header">
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link to="/Grant">授权管理</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ experimentSetName }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>

      <!-- 批次数据表格 -->
      <a-table
        :columns="columns"
        :data-source="batchData"
        :pagination="false"
        :scroll="{ y: '35vh' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a @click="handleViewExperiments(record)">查看实验</a>
            </span>
          </template>
        </template>
      </a-table>

      <!-- 实验集文件表格 -->
      <a-table
        :columns="fileColumns"
        :data-source="fileData"
        :pagination="false"
        :scroll="{ y: '30vh' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'file_size'">
            {{ formatFileSize(record.file_size) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button
              :loading="record.downloading"
              @click="handleDownloadFile(record)"
            >
              {{ record.downloading ? `${record.progress}%` : '下载' }}
            </a-button>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import { message } from 'ant-design-vue';
import axiosInstance from '@/axios/axios.js';

export default defineComponent({
  name: 'AuthorizedBatch',
  data() {
    return {
      experimentSetName: '',
      batchData: [],
      fileData: [],
      columns: [
        {
          title: '批次名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '操作',
          key: 'action',
          width: 150
        }
      ],
      fileColumns: [
        {
          title: '文件名',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '文件类型',
          dataIndex: 'file_type',
          key: 'file_type'
        },
        {
          title: '文件大小',
          dataIndex: 'file_size',
          key: 'file_size'
        },
        {
          title: '文件类别',
          dataIndex: 'file_category',
          key: 'file_category'
        },
        {
          title: '操作',
          key: 'action',
          width: 100
        }
      ]
    };
  },
  created() {
    // 从路由参数中获取数据
    const { experimentSetName, batchData } = this.$route.query;
    this.experimentSetName = experimentSetName || '未知实验集';
    
    try {
      this.batchData = JSON.parse(batchData || '[]');
      console.log('Parsed batch data:', this.batchData);
      
      // 确保每个批次对象都有必要的属性，同时保留所有原始字段
      this.batchData = this.batchData.map(batch => ({
        ...batch,  // 保留所有原始字段
        key: batch.batch_id || batch._temp_comment,
        name: batch.name || '未命名批次',
        description: batch.description || ''
      }));

      console.log('Batch data with all fields:', this.batchData.map(batch => ({
        id: batch.batch_id,
        name: batch.name,
        tx_hash: batch.tx_hash,
        height: batch.height,
        all_fields: Object.keys(batch)
      })));
      
      console.log('Processed batch data:', this.batchData);

      // 初始化实验集文件数据
      try {
        const allData = JSON.parse(this.$route.query.allData || '{}');
        const experimentSetFiles = allData.experimentSetFiles || [];
        this.fileData = experimentSetFiles.map(file => ({
          ...file,
          key: file.file_id || file._temp_comment,
          downloading: false,
          progress: 0
        }));
        console.log('Processed file data:', this.fileData);
      } catch (error) {
        console.error('解析文件数据失败:', error);
        message.error('解析文件数据失败');
        this.fileData = [];
      }
    } catch (error) {
      console.error('解析批次数据失败:', error);
      message.error('解析批次数据失败');
      this.batchData = [];
      this.fileData = [];
    }
  },
  methods: {
    formatFileSize(bytes) {
      if (!bytes) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    async handleDownloadFile(record) {
      if (record.downloading) return;

      // 更新文件状态
      const index = this.fileData.findIndex(f => f.file_id === record.file_id);
      if (index !== -1) {
        this.fileData[index].downloading = true;
        this.fileData[index].progress = 0;
      }

      try {
        // 获取授权信息
        const userAddress = this.$cookies.get("userAddress");
        const accessId = this.$route.query.accessId;
        if (!userAddress || !accessId) {
          console.error('Missing required auth info:', { userAddress, accessId });
          message.error('授权信息不完整');
          return;
        }

        // 构造共享路径
        const sharedPath = `shared/${userAddress}/${accessId}/${record.relative_path}`;
        const encodedPath = encodeURIComponent(sharedPath);
        console.log('Downloading file with shared path:', encodedPath);

        const response = await axiosInstance({
          method: "GET",
          url: `/download/file?relativePath=${encodedPath}`,
          responseType: "blob",
          onDownloadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              if (index !== -1) {
                this.fileData[index].progress = progress;
              }
            }
          }
        });

        // 创建下载链接
        const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = blobUrl;
        link.setAttribute('download', record.name);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(blobUrl);

        message.success('下载完成');
      } catch (error) {
        console.error('下载文件失败:', error);
        message.error(`下载失败: ${error.response?.data?.message || error.message}`);
      } finally {
        // 重置文件状态
        if (index !== -1) {
          this.fileData[index].downloading = false;
          this.fileData[index].progress = 0;
        }
      }
    },
    handleViewExperiments(record) {
      try {
        // 获取该批次的实验数据
        const experiments = this.filterExperimentsByBatchId(record.batch_id);
        console.log('Filtered experiments:', experiments);

        if (experiments.length === 0) {
          message.warning('该批次下没有实验数据');
          return;
        }

        // 导航到实验页面
        this.$router.push({
          path: '/Grant/AuthorizedExperiment',
          query: {
            experimentSetName: this.experimentSetName,
            batchName: record.name,
            batchId: record.batch_id,
            experimentSetId: this.$route.query.experimentSetId, // 添加实验集ID
            experimentData: JSON.stringify(experiments),
            allData: this.$route.query.allData, // 传递完整数据
            accessId: this.$route.query.accessId // 传递授权ID
          }
        });
      } catch (error) {
        console.error('处理实验数据失败:', error);
        message.error('处理实验数据失败');
      }
    },
    filterExperimentsByBatchId(batchId) {
      try {
        const allData = JSON.parse(this.$route.query.allData || '{}');
        const experiments = allData.experiments || [];
        const filteredExperiments = experiments.filter(exp => exp.batch_id === batchId);

        console.log('Filtered experiments with all fields:', filteredExperiments.map(exp => ({
          id: exp.experiment_id,
          name: exp.experiment_name,
          tx_hash: exp.tx_hash,
          height: exp.height,
          all_fields: Object.keys(exp)
        })));

        return filteredExperiments;
      } catch (error) {
        console.error('过滤实验数据失败:', error);
        return [];
      }
    }
  }
});
</script>

<style scoped>
.header {
  margin-bottom: 24px;
}
</style>